import { memo, useEffect, useState } from "react";
import { useEditUserInfo, useGetUserInfo } from "../../service/user";
import DataDisplay_content from "../../baseUI/dataDisplay_content/idnex";
import {
  Button,
  Form,
  ImageUploader,
  Input,
  TextArea,
  Toast,
} from "antd-mobile";
import EditUserInfoStyle from "./style";
import { AUTH_TOKEN } from "../../constant";
import { CheckOutline, CloseOutline } from "antd-mobile-icons";

const EditUserInfo = memo(() => {
  const { data, loading } = useGetUserInfo();
  const [form] = Form.useForm();
  const { editUserInfo, editLoading } = useEditUserInfo();
  const [avater, setAvater] = useState<[{ url: string }]>();
  useEffect(() => {
    setAvater(
      data?.avatar?.length > 0
        ? [{ url: data?.avatar }]
        : [{ url: "https://danyun.oss-cn-chengdu.aliyuncs.com/brand.png" }]
    );
  }, [data]);
  useEffect(() => {
    if (editLoading) {
      Toast.show({
        icon: "loading",
      });
    }
  }, [editLoading]);
  const token = localStorage.getItem(AUTH_TOKEN);
  const beforeUpload = (file: File) => {
    const isIMG =
      file.type === "image/png" ||
      file.type === "image/jpeg" ||
      file.type === "image/jpg";
    if (!isIMG) {
      Toast.show("请上传正确的图片格式（png,jpeg,jpg,jiff）！");
      return null;
    }
    if (file.size > 1024 * 1024) {
      Toast.show("请选择小于 1M 的图片");
      return null;
    }
    return file;
  };
  const uploadImg = async (file: File) => {
    const formData = new FormData();
    formData.append("file", file);
    void fetch(`${import.meta.env.VITE_BASE_URL}/upload/${data?.id}/true`, {
      method: "post",
      body: formData,
      headers: {
        Authorization: `Bearer ${token!}`,
      },
    })
      .then((response) => {
        if (!response.ok) {
          Toast.show({
            icon: <CloseOutline />,
            content: "更新失败",
          });
        }
        return response.json(); // if the server response is JSON
      })
      .then(() => {
        Toast.show({
          icon: <CheckOutline />,
          content: "更新成功！",
        });
      })
      .catch(() => {
        Toast.show({
          icon: <CloseOutline />,
          content: "更新失败",
        });
      });
    return {
      url: `${import.meta.env.VITE_BASE_URL}/static/` + file.name,
    };
  };
  const submitClick = async () => {
    const res = (await form.validateFields()) as {
      name: string;
      desc: string;
      tel: string;
    };
    if (
      res.name === data.name &&
      res.desc === data.desc &&
      res.tel === data.tel
    )
      return;
    const result = await editUserInfo(res);
    if (result.code) {
      Toast.show({
        icon: <CheckOutline />,
        content: "更新成功！",
      });
    } else {
      Toast.show({
        icon: <CloseOutline />,
        content: "更新失败",
      });
    }
  };
  return (
    <EditUserInfoStyle>
      <DataDisplay_content loading={loading} title="编辑个人资料">
        <div className="avater">
          <ImageUploader
            value={avater}
            onChange={(value) => setAvater(value as [{ url: string }])}
            maxCount={1}
            beforeUpload={beforeUpload}
            upload={uploadImg}
          />
        </div>

        <Form
          layout="horizontal"
          initialValues={data}
          form={form}
          footer={
            <Button
              block
              type="submit"
              color="primary"
              size="large"
              onClick={submitClick}
            >
              提交
            </Button>
          }
        >
          <Form.Item name="tel" label="手机号">
            <Input placeholder="请填写手机号" />
          </Form.Item>
          <Form.Item name="name" label="名称">
            <Input
              placeholder={
                data?.name.length > 0 ? data?.name : `淡云教育用户${data?.id}`
              }
            />
          </Form.Item>
          <Form.Item name="desc" label="简介">
            <TextArea showCount placeholder="请输入简介" maxLength={100} />
          </Form.Item>
        </Form>
      </DataDisplay_content>
    </EditUserInfoStyle>
  );
});

export default EditUserInfo;
